<template>
  <PublicPage bgColor="#F5F5F5">
    <u-form
      labelPosition="left"
      :model="formData"
      :rules="rules"
      :labelWidth="100"
      ref="form"
      errorType="border-bottom">
      <view class="px-4 pt-3 bg-white">
        <u-form-item label="机构名称" prop="cname" required>
          <view v-if="disabled" class="text-right fz-15 text-[30rpx] flex-1">
            {{ formData.cname }}
          </view>
          <up-input
            v-else
            v-model="formData.cname"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入机构名称"></up-input>
        </u-form-item>
        <u-form-item label="机构地址" prop="province" required>
          <AddressPick
            :province="formData.province"
            :city="formData.city"
            :distincts="formData.distincts"
            :disabled="disabled"
            @onChange="onChangeAddress"
            placeholder="请选择地址" />
        </u-form-item>
        <u-form-item label="详细地址" prop="address" required>
          <view v-if="disabled" class="text-right fz-15 text-[30rpx] flex-1">
            {{ formData.address }}
          </view>
          <up-input
            v-else
            v-model="formData.address"
            :disabled="disabled"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入详细地址"></up-input>
        </u-form-item>
        <u-form-item label="机构联系人" prop="contactName" required>
          <up-input
            v-model="formData.contactName"
            :disabled="disabled"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入联系人姓名"></up-input>
        </u-form-item>
        <u-form-item label="联系人电话" prop="phone">
          <up-input
            v-model="formData.phone"
            :disabled="disabled"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入联系人电话"></up-input>
        </u-form-item>
        <u-form-item label="管理员账号" prop="adminacc" required>
          <up-input
            v-model="formData.adminacc"
            :disabled="!!formData.id"
            disabledColor="#FFF"
            border="none"
            inputAlign="right"
            placeholder="请输入管理后台的登录账号"></up-input>
        </u-form-item>
        <u-form-item label="机构等级" prop="levels">
          <SelectPick
            v-model="formData.levels"
            :dictList="levelsOptions"
            placeholder="请选择机构等级"
            :disabled="disabled"
            @open="getLevelsOptions" />
        </u-form-item>
        <u-form-item label="机构类型" prop="comtype">
          <SelectPick
            v-model="formData.comtype"
            :dictList="comtypeOptions"
            placeholder="请选择机构类型"
            :disabled="disabled"
            @open="getComtypeOptions" />
        </u-form-item>
        <u-form-item label="机构跟进人" prop="businessUserId" required>
          <view
            class="text-[30rpx] w-full flex justify-end items-center"
            @click="goFollowUser">
            <text v-if="selectedBusiness?.nickName">
              {{ selectedBusiness.nickName }}
            </text>
            <text v-else class="u-light-color">
              {{ disabled ? '-' : '请选择机构跟进人' }}
            </text>
            <i v-if="!disabled" class="iconfont rightArrow">&#xe60d;</i>
          </view>
        </u-form-item>
        <u-form-item label="归属部门">
          <view
            class="text-[30rpx] w-full flex justify-end items-center"
            :class="{
              'u-light-color': !selectedBusiness?.dept.deptName
            }">
            {{ selectedBusiness?.dept.deptName || '-' }}
          </view>
        </u-form-item>
        <u-form-item
          label="机构门头（用于展示给患者和PAD上浏览）"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          prop="cimg1">
          <UploadImg
            v-model="formData.cimg1"
            name="cimg1"
            bottom-tips="只支持.jpg.png 格式，400*400尺寸"
            :disabled="disabled"></UploadImg>
        </u-form-item>
        <u-form-item
          label="机构营业执照"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          prop="businessimg"
          required>
          <UploadImg
            v-model="formData.businessimg"
            name="businessimg"
            tips="上传营业执照"
            bottom-tips="只支持.jpg.png 格式"
            :disabled="disabled"></UploadImg>
        </u-form-item>
        <u-form-item
          label="医疗机构执业许可证"
          labelWidth="100%"
          :customStyle="{ 'flex-direction': 'column' }"
          prop="miplImg"
          required>
          <UploadImg
            v-model="formData.miplImg"
            name="miplImg"
            tips="上传许可证"
            bottom-tips="只支持.jpg.png 格式"
            :disabled="disabled"></UploadImg>
        </u-form-item>
      </view>
    </u-form>

    <FixedButton v-if="!disabled && formData?.id" placeholder>
      <u-button type="primary" :loading="loading" @click="submit">
        重新提交审核
      </u-button>
    </FixedButton>
    <div v-else-if="!disabled" class="p-4">
      <view class="grid grid-cols-2 gap-x-5">
        <u-button
          type="primary"
          plain
          :loading="loading"
          @click="submit('addExport')">
          提交并新增医生
        </u-button>
        <u-button type="primary" :loading="loading" @click="submit">
          提交审核
        </u-button>
      </view>
    </div>
  </PublicPage>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/user';
import FixedButton from '@/components/fixedButton.vue'
import SelectPick from '@/components/selectPick.vue'
import { DictItemTypes, dictData } from '@/api/dict'
import { OrganizationInfoTypes } from '@/types/organization'
import UploadImg from '@/components/upload.vue'
import { useExpertStore } from '@/stores/expert'
import { addCompany, companyDetails, editCompany } from '@/api/organization'
import AddressPick from '@/components/addressPick.vue'
import { setRefreshRouters } from '@/hooks/refreshPage'

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

// 详情页
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
})

const expertStore = useExpertStore()
const { selectedBusiness } = storeToRefs(expertStore) // 获取已选择机构
const { setSelectedBusiness } = expertStore

const formData = ref<OrganizationInfoTypes>({
  cname: '',
  province: '',
  city: '',
  distincts: '',
  address: '',
  contactName: '',
  phone: '',
  levels: '',
  comtype: '',
  businessUserId: 0,
  businessUserName: '',

  cimg1: '',
  businessimg: '',
  miplImg: '',

  adminname: '',
  honorific: '0',
  mobile: '',
  adminacc: ''
})

const rules = reactive({
  cname: [
    {
      type: 'string',
      required: true,
      message: '请输入机构名称',
      trigger: ['blur', 'change']
    }
  ],
  province: [
    {
      type: 'string',
      required: true,
      message: '请选择机构地址',
      trigger: ['change']
    }
  ],
  address: [
    {
      type: 'string',
      required: true,
      message: '请输入机构详细地址',
      trigger: ['blur', 'change']
    }
  ],
  contactName: [
    {
      type: 'string',
      required: true,
      message: '请输入机构详细地址',
      trigger: ['blur', 'change']
    }
  ],
  adminacc: [
    {
      type: 'string',
      required: true,
      message: '请输入管理员账号',
      trigger: ['blur', 'change']
    }
  ],
  businessUserId: [
    {
      type: 'number',
      required: true,
      message: '请选择机构跟进人',
      trigger: ['change']
    }
  ],
  businessimg: [
    {
      type: 'string',
      required: true,
      message: '请上传机构营业执照',
      trigger: ['change']
    }
  ],
  miplImg: [
    {
      type: 'string',
      required: true,
      message: '请上传医疗机构执业许可证',
      trigger: ['change']
    }
  ]
})

// 详情页初始化信息
const refresh = (info: OrganizationInfoTypes) => {
  formData.value = info
  setSelectedBusiness({
    userId: info.businessUserId,
    avatar: '',
    nickName: info.businessUserName,
    dept: {
      deptName: info.businessDeptName // 部门名称
    }
  })
}

// 编辑回显
onLoad(async (options) => {
  !props.disabled && uni.setNavigationBarTitle({ title: '新增机构' })
  // 获取机构信息
  if (options?.id) {
    !props.disabled && uni.setNavigationBarTitle({ title: '编辑机构' })
    const { data } = await companyDetails(options.id)
    refresh(data)
  }else{
    setSelectedBusiness({
      userId: userInfo.value.userId,
      avatar: userInfo.value.avatar,
      nickName: userInfo.value.nickName,
      dept: {
        deptName: userInfo.value.deptName // 部门名称
      }
    })
  }
})

const loading = ref(false)
const _that = getCurrentInstance()
const submit = (goType?: string) => {
  formData.value.businessUserId = selectedBusiness.value?.userId as number
  console.log(JSON.parse(JSON.stringify(unref(formData))), '提交的数据')
  ;(_that?.refs.form as any)
    .validate()
    .then(async () => {
      loading.value = true
      if (unref(formData)?.id) {
        // 修改
        await editCompany(unref(formData)).finally(() => {
          loading.value = false
        })
        // 刷新详情页和列表页
        setRefreshRouters([
          '/pages/organization/organizationDetail',
          '/pages/organization/organization'
        ])
      } else {
        // 新增
        formData.value.adminname = formData.value.contactName // 管理员姓名 -默认赋值单位联系人
        formData.value.mobile = formData.value.phone // 管理员手机号 -默认赋值单位联系人电话
        const { data } = await addCompany(unref(formData)).finally(() => {
          loading.value = false
        })
        setRefreshRouters(['/pages/organization/organization'])
        if (goType) {
          // 刷新列表页
          uni.$u.route({
            type: 'redirectTo',
            url: '/pages/expert/editExport',
            params: { comId: data }
          })
          return
        }
      }

      uni.showToast({
        title: '提交成功',
        complete: function () {
          setTimeout(() => {
            uni.$u.route({
              type: 'navigateBack',
              delta: 1
            })
          }, 1500)
        }
      })
    })
    .catch((err: any) => {
      uni.showToast({
        title: err[0].message,
        icon: 'none'
      })
    })
}

// 选择地址
const onChangeAddress = (e: any) => {
  formData.value.province = e.province
  formData.value.city = e.city
  formData.value.distincts = e.distincts
}

// 获取机构等级
const levelsOptions = ref<DictItemTypes[]>([])
const getLevelsOptions = async () => {
  const { data } = await dictData('company_level') // 获取字典中的数据
  levelsOptions.value = data
}
getLevelsOptions()

// 获取机构类型
const comtypeOptions = ref<DictItemTypes[]>([])
const getComtypeOptions = async () => {
  const { data } = await dictData('company_type') // 获取字典中的数据
  comtypeOptions.value = data
}
getComtypeOptions()

// 跳转去选择机构跟进人
const goFollowUser = () => {
  uni.$u.route({
    type: 'navigateTo',
    url: '/pages/organization/followUser'
  })
}
onUnload(() => {
  setSelectedBusiness() // 清除选择的跟进人
})


defineExpose({ refresh })
</script>

<style lang="scss" scoped></style>
